package com.jxt.myapp.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.jxt.myapp.service.imp.PermissionsService;

public class CustomUserDetailsService implements UserDetailsService {

	private static final Logger logger = LoggerFactory
			.getLogger(CustomUserDetailsService.class);

	PermissionsService permissionsService = new PermissionsService();
	

	public PermissionsService getPermissionsService() {
		return permissionsService;
	}

	public void setPermissionsService(PermissionsService permissionsService) {
		this.permissionsService = permissionsService;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		UserDetails user = null;

		logger.info("username:" + username);
		logger.info("***********************");

		com.jxt.myapp.domain.User userDB = permissionsService
				.getUserByLoginName(username);

		if (userDB == null) {
			throw new UsernameNotFoundException("用户" + username + "不存在!");
		}

		user = new User(username, "admin", true, true, true, true,
				getAuthorities());
		logger.info("***********************");
		logger.info("userDetails:" + user);
		return user;
	}

	public Collection<GrantedAuthority> getAuthorities() {

		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();

		authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

		return authList;
	}

}
